//
//  BaseTableViewController.m
//  1-MushroomStreet-自定义tabbar
//
//  Created by xmg on 15/12/14.
//  Copyright © 2015年 grx. All rights reserved.
//

#import "BaseTableViewController.h"
#import "GRXHeaderRefresh.h"
#import "statusCell.h"
#import "NetworkTools.h"
#import "StatusListModel.h"
#import <MJExtension/MJExtension.h>
#import <MJRefreshAutoNormalFooter.h>

@interface BaseTableViewController ()

/**当前课件的tableView*/
@property (nonatomic, weak) UIScrollView *tempScrollView;

/**<#name#>*/
@property (nonatomic,assign)CGFloat tempOffsetY;

/**模型数组*/
@property (nonatomic,strong)NSMutableArray<StatusListModel *> *itemArray;

/**若指定此参数，则返回ID比since_id大的微博（即比since_id时间晚的微博），默认为0。 */
@property (nonatomic,assign)NSInteger since_id;

/**若指定此参数，则返回ID小于或等于max_id的微博，默认为0。  */
@property (nonatomic,assign)NSInteger max_id;

/**上拉加载更多*/
@property (nonatomic,assign)BOOL flag;

/**测试用view*/
@property (nonatomic, weak) UIView *test;


@end

@implementation BaseTableViewController


#pragma mark ---
#pragma mark 懒加载
- (NSMutableArray *)itemArray{
    if (!_itemArray) {
        _itemArray = [[NSMutableArray alloc] init];
        
    }
    return _itemArray;
}



#pragma mark ---
#pragma mark 系统回调方法
static NSString *statusID = @"statusCell";

- (void)viewDidLoad {
    [super viewDidLoad];
    
    //对view的初始化设置
    [self setUpView];
    
    //集成刷新控件
    [self setUpRefresh];
    
    //接收通知
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(tempTableViewScroll:) name:GRXChangeChildViewControllerNotification object:nil];
    
    self.tableView.rowHeight = 230;

    [self.tableView registerNib:[UINib nibWithNibName:@"statusCell" bundle:nil] forCellReuseIdentifier:statusID];
    
}

- (void)viewDidAppear:(BOOL)animated{
    [super viewDidAppear:animated];
    

    
}

- (void)viewDidLayoutSubviews{
    [super viewDidLayoutSubviews];
    self.test.frame = CGRectMake(0, 0, kScreenW, kScreenH);
}



- (void)setUpRefresh
{
    
    self.flag = NO;
    
    self.tableView.mj_header = [GRXHeaderRefresh headerWithRefreshingTarget:self refreshingAction:@selector(loadNewData)];
    [self.tableView.mj_header beginRefreshing];
    
    self.tableView.mj_footer = [MJRefreshBackNormalFooter footerWithRefreshingTarget:self refreshingAction:@selector(loadMoreData)];
}

#pragma mark ---对view的初始化设置
- (void)setUpView{
    self.tableView.backgroundColor = [UIColor clearColor];
    self.tableView.showsHorizontalScrollIndicator = NO;
    self.tableView.showsVerticalScrollIndicator = NO;
}

#pragma mark ---通知方法
- (void)tempTableViewScroll:(NSNotification *)notification{

    //取出当前显示的tableView
    UIScrollView *tempScrollView = notification.userInfo[@"scrollView"];

    if ([tempScrollView isEqual: self.tableView]) return;
    if (self.tableView == nil) return;
    
    //当前滚动的tableView的偏移量的y值如果大于负的选项卡的高度,那么tableView偏移量的y值就等于负的选项卡的高度
    if (tempScrollView.contentOffset.y > -GRXAlternativeHeight) {
        
        CGPoint offset = CGPointMake(0, -GRXAlternativeHeight);
        
        if (self.tableView.contentOffset.y < -GRXAlternativeHeight) {
            self.tableView.contentOffset = offset;
        }
    }else {
        self.tableView.contentOffset = tempScrollView.contentOffset;
    }
}

#pragma mark ---数据加载
- (void)loadNewData{
    NSString *path = @"2/statuses/friends_timeline.json";
    
    NSMutableDictionary *parameter = [NSMutableDictionary dictionary];
    parameter[@"access_token"] = access_token;
    parameter[@"since_id"] = 0;
    parameter[@"max_id"] = 0;
    
    //利用工具类进行网络请求
    [NetworkTools loadDataFromServerWithPath:path parameters:parameter resultObject:^(id responseObject) {
        
        NSDictionary *dict = responseObject;
        
        //字典转模型
        self.itemArray = [StatusListModel mj_objectArrayWithKeyValuesArray:dict[@"statuses"]];
        
        // 刷新表格
        [self.tableView reloadData];
        
        //结束刷新
        [self.tableView.mj_header endRefreshing];
    }];
    
}

#pragma mark ---加载更多
- (void)loadMoreData{
    
    self.flag = YES;
    
    // 取消之前的请求
    NetworkTools *tools = [NetworkTools shareNetworkTools];
    [tools.tasks makeObjectsPerformSelector:@selector(cancel)];
    
     NSString *path = @"2/statuses/friends_timeline.json";
    
    // 拼接请求参数
    NSMutableDictionary *parameter = [NSMutableDictionary dictionary];
    parameter[@"access_token"] = access_token;

    parameter[@"since_id"] = @([self.itemArray lastObject].user_id);
    parameter[@"max_id"] = @(self.max_id);
    
    [NetworkTools loadDataFromServerWithPath:path parameters:parameter resultObject:^(id responseObject) {
        
        self.since_id = [responseObject[@"id"] integerValue];
        self.max_id = [responseObject[@"max_id"] integerValue];
        
        NSArray *array = [StatusListModel mj_objectArrayWithKeyValuesArray:responseObject[@"statuses"]];
        
        [self.itemArray addObjectsFromArray:array];
        
        [self.tableView reloadData];
        
        [self.tableView.mj_footer endRefreshing];
        
        self.flag = NO;
    }];
}


#pragma mark ---数据源
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    
    
        return self.itemArray.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    
   
    
    statusCell *cell = [tableView dequeueReusableCellWithIdentifier:statusID forIndexPath:indexPath];
    
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    
    cell.model = self.itemArray[indexPath.row];
    
    return cell;
}

#pragma mark ---UITabelView代理
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    StatusListModel *model = self.itemArray[indexPath.row];
    return model.cellHeight;
}

#pragma mark ---UIScrollView代理
//设置scrollView的滚性滚动速度
- (void)scrollViewDidEndDragging:(UIScrollView *)scrollView willDecelerate:(BOOL)decelerat{
    scrollView.decelerationRate = 0;
}

//能够监听所有的tableView的滚动
- (void)scrollViewDidScroll:(UIScrollView *)scrollView{
    //让所有的tableView都能接收到通知(把当前滚动的tableView传递出去)
    NSDictionary *dict = @{@"scrollView":scrollView};
    
    //发送通知
    [[NSNotificationCenter defaultCenter] postNotificationName:GRXChangeChildViewControllerNotification object:nil userInfo:dict];
}

#pragma mark ---销毁通知
- (void)dealloc{
    //销毁通知
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}



@end
